<template>
  <div>
    <!-- 搜索与操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.searchName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入商品名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 商品卡片列表 -->
    <div class="card-container">
      <el-card
          :body-style="{ padding: '10px', cursor: 'pointer' }"
          v-for="(goods, index) in data.tableData"
          :key="index"
          shadow="hover"
          @mouseover="showFullDescription(index)"
          @mouseleave="hideFullDescription(index)"
          style="width: 240px; margin: 10px;"
      >
        <img :src="goods.image" class="image" v-if="goods.image" />
        <div style="padding: 14px;">
          <span>{{ goods.goodsName }}</span>
          <div class="description">
            <span v-if="!data.fullDescription[index]">{{ shortDescription(goods.description) }}...</span>
            <span v-else>{{ goods.description }}</span>
          </div>
          <div>所需积分：{{ goods.points }}</div>
          <div>库存：{{ goods.stock }}</div>
          <div>状态：{{ goods.status === 0 ? '上架' : '下架' }}</div>
          <div style="margin-top: 10px;">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(goods)"></el-button>
            <el-button type="success" :icon="Top" v-if="goods.status === 1" @click="toggleStatus(goods.id, 0)">上架</el-button>
            <el-button type="warning" :icon="Bottom" v-else @click="toggleStatus(goods.id, 1)">下架</el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(goods.id)"></el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"/>
    </div>

    <!-- 编辑或新增商品对话框 -->
    <el-dialog title="商品信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="80px" style="padding: 20px">
        <el-form-item label="商品名称">
          <el-input v-model="data.form.goodsName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" v-model="data.form.description" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="所需积分">
          <el-input-number v-model="data.form.points" :min="0" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model="data.form.stock" :min="0" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, watch } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Top, Bottom } from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  searchName: null,
  ids: [],
  fullDescription: [] // 初始化为空数组
});

// 监听tableData变化，同步更新fullDescription的状态
watch(() => data.tableData, (newVal) => {
  data.fullDescription = newVal.map(() => false);
}, { immediate: true });

// 加载商品列表
const load = () => {
  request.get('/pointsGoods/page', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      searchName: data.searchName
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list || [];
      data.total = res.data.total;
    }
  })
};

// 新增商品
const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
};

// 编辑商品
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

// 删除单个商品
const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(() => {
    request.delete(`/pointsGoods/delete/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => console.error(err));
};

// 批量删除商品
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(() => {
    request.delete("/pointsGoods/delete/batch", { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => console.error(err));
};

// 文件上传成功处理
const handleFileUpload = (res) => {
  data.form.image = res.data;
};

// 保存商品（新增或更新）
const save = () => {
  if (data.form.id) {
    // 更新商品
    request.put(`/pointsGoods/update/${data.form.id}`, data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.formVisible = false;
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    // 新增商品
    request.post('/pointsGoods/add', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.formVisible = false;
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

// 切换商品状态（上架/下架）
const toggleStatus = (id, status) => {
  request.put(`/pointsGoods/update/${id}`, { status }).then(res => {
    if (res.code === '200') {
      ElMessage.success(status === 1 ? '下架成功' : '上架成功');
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 显示完整描述
const showFullDescription = (index) => {
  data.fullDescription[index] = true;
};

// 隐藏完整描述
const hideFullDescription = (index) => {
  data.fullDescription[index] = false;
};

// 截断描述
const shortDescription = (description) => {
  if (description.length > 30) {
    return description.substring(0, 30);
  }
  return description;
};

// 重置搜索条件
const reset = () => {
  data.searchName = null;
  load();
};

// 初始化加载商品列表
load();
</script>

<style scoped>
.card-container {
  display: flex;
  flex-wrap: wrap;
}
.image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.description {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 40px;
  line-height: 20px;
}
/* 确保按钮不会被裁剪 */
.el-button--success, .el-button--warning {
  padding: 10px 20px;
  font-size: 14px;
}
</style>
